package com.dinadi.yidi.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.dinadi.yidi.R;
import com.dinadi.yidi.bean.UpdateAppRequest;
import com.dinadi.yidi.http.FileHttpCallback;
import com.dinadi.yidi.http.ServiceUtil;
import com.dinadi.yidi.service.UpDataVersionService;
import com.dinadi.yidi.ui.activity.IntegralGiftActivity;
import com.dinadi.yidi.utils.app.AppManager;

import java.io.File;

import de.greenrobot.event.EventBus;

/**
 * Created by mimizaijia on 2016/12/2.
 * 应用更新的管理类
 */

public class UpdateManager {
    public static String DOWNLOAD_DIR = Environment.getExternalStorageDirectory()
            + File.separator
            + CommonUtil.getContext().getPackageName()
            + File.separator
            + "download";
    private Activity context;
    private ProgressBar mProgress;
    AlertDialog.Builder dialog;
    private static final int MESSAGE_PROGRESS = 44;
    private static final int MESSAGE_LOAD_SUCCESS = 45;
    private static final int MESSAGE_LOAD_FAILURE = 46;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_PROGRESS:
                    int por = (int) msg.obj;
                    mProgress.setProgress(por);
                    break;
                case MESSAGE_LOAD_SUCCESS:
                    File file = (File) msg.obj;
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.setDataAndType(Uri.fromFile(file),
                            "application/vnd.android.package-archive");
                    CommonUtil.getContext().startActivity(i);
                    AppManager.getAppManager().finishAllActivity();
                    System.exit(0);
                    break;
            }
        }
    };

    public UpdateManager(Activity context) {
        this.context = context;
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public String getCurrentVersion(Context context) {
        String version = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            String curVersionName = info.versionName;
            String curVersionCode = String.valueOf(info.versionCode);
            version = curVersionName;
            TLog.error(curVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        return version;
    }


    /**
     * 获取版本号名字
     *
     * @param context
     * @return
     */
    public String getCurrentVersionName(Context context) {
        String curVersionName = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            curVersionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        return curVersionName;
    }


    public void setUpdateDialog(final UpdateAppRequest updateAppBean) {
        //如果版本最新，则不需要更新
//        if (updateAppBean.getIsforce().equals("1")) {
//            //强制升级,则没有取消按钮
//            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
//            dialog.setTitle("发现新版本 ：" + updateAppBean.getEdition());
//            dialog.setMessage(updateAppBean.getEditionmsg());
//            dialog.setPositiveButton("现在更新", new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface arg0, int arg1) {
//                    // TODO Auto-generated method stub
//                    arg0.dismiss();
//                    goUpload(updateAppBean);
//                }
//            });
//            dialog.create();
//            dialog.setCancelable(false);
//            dialog.show();
//
//        } else if (updateAppBean.getIsforce().equals("0")) {
        //非强制升级
//        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
//        dialog.setTitle("发现新版本 ：" + updateAppBean.getVersionNo());
//        dialog.setMessage(updateAppBean.getDescription());
//        dialog.setPositiveButton("现在更新", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface arg0, int arg1) {
//                // TODO Auto-generated method stub
//                arg0.dismiss();
//
//                //启动后台进行下载
//                Intent intent = new Intent(context, UpDataVersionService.class);
//                intent.putExtra("downAPKUrl", updateAppBean.getDownUrl());
//                context.startService(intent);
//                EventBus.getDefault().post("1");
//                //  goUpload(updateAppBean);
//            }
//        });
//        //是否强制更新
//        dialog.setNegativeButton("稍后更新", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface arg0, int arg1) {
//                // TODO Auto-generated method stub
//                arg0.dismiss();
//                EventBus.getDefault().post("1");
//            }
//        });
//        dialog.create();
//        dialog.setCancelable(false);
//        dialog.show();


        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = context.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) context.getLayoutInflater().inflate(R.layout.popupwindow_update, null);
        FrameLayout layout2 = (FrameLayout) context.getLayoutInflater().inflate(R.layout.activity_main, null);
        popupWindow.setPopupWindow(context, windowHeight, layout, layout2, Gravity.CENTER);

        TextView update_title = (TextView) layout.findViewById(R.id.update_title);
        TextView update_content = (TextView) layout.findViewById(R.id.update_content);
        ImageView img_update = (ImageView) layout.findViewById(R.id.img_update);
        ImageView img_refuse = (ImageView) layout.findViewById(R.id.img_refuse);
        update_title.setText("版本升级 (" + updateAppBean.getVersionNo() + ")");
//        stringChang();
        update_content.setText(StringChange.stringChang(updateAppBean.getDescription()));


        img_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                //启动后台进行下载
                Intent intent = new Intent(context, UpDataVersionService.class);
                intent.putExtra("downAPKUrl", updateAppBean.getDownUrl());
                context.startService(intent);
                EventBus.getDefault().post("1");
            }
        });
        img_refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().post("1");
            }
        });
        //   }

    }

    public void goUpload(UpdateAppRequest updateAppBean) {
        //去下载，并弹出下载进度
        showDownloadDialog();
        ServiceUtil.requestDownAPK(updateAppBean.getDownUrl(), DOWNLOAD_DIR, "yidi.apk",
                null, new FileHttpCallback(DOWNLOAD_DIR, "yidi.apk") {
                    @Override
                    public void onSuccess(File response) {
                        Message message = new Message();
                        message.what = MESSAGE_LOAD_SUCCESS;
                        message.obj = response;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void onFailure(String error) {

                    }

                    @Override
                    public void onProgress(float progress, long total) {
                        Message message = new Message();
                        message.what = MESSAGE_PROGRESS;
                        int pro = (int) (progress * 100f);
                        message.obj = pro;
                        handler.sendMessage(message);

                    }
                });
    }


    public void showDownloadDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle("正在更新,请稍等");
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        dialog.setView(v);

        dialog.create();
        dialog.setCancelable(false);
        dialog.show();
    }


}
